<template>
  <!-- 新建/编辑订单 -->
  <div ref="wrap">
    <div class="topBtnWrap">
      <div>
        <el-button type="primary" size="small" :disabled="editData.cConfirm" @click="batchPartSelectVisible = true">批量订货</el-button>
        <!-- <el-button type="primary" size="small">订货建议</el-button> -->
        <el-button type="primary" size="small" disabled>portal查询</el-button>
        <el-button type="primary" size="small" :disabled="selectedOrderTypeVal != '9' || editData.cConfirm" @click="handlePushSuggestBtnClick">推式建议</el-button>
        <AjaxButton type="primary" size="small" :disabled="editData.cConfirm" :click="handleFundForecast">资金预测</AjaxButton>
        <el-button type="primary" size="small" :disabled="editData.cConfirm" @click="showPackgingOrder">打包订货</el-button>
      </div>
      <div>
        <el-button size="small" :disabled="!isAdd" @click="resetPageData">重 置</el-button>
      </div>
    </div>
    <!-- 参考单据 -->
    <BreakSpace label="参考单据创建" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <!-- <AjaxButton type="primary" size="mini" style="margin-bottom: 10px" :disabled="editData.cConfirm" :click="handleGetBillDetail">接收参考单据明细</AjaxButton> -->
    <FormPanel ref="billCreateForm" :list="billsCreateFormList" :cols="4" :labelWidth="85" :isSubmitBtn="false"></FormPanel>
    <!-- 订单数据 -->
    <BreakSpace label="采购订单" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <FormPanel ref="purchaseForm" :list="purchaseFormList" :cols="4" :labelWidth="85" :isSubmitBtn="false"></FormPanel>
    <!-- 订单状态 -->
    <BreakSpace label="订单状态" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
    <FormPanel :list="statusFormList" :cols="4" :labelWidth="85" :isSubmitBtn="false"></FormPanel>
    <FilterTable
      ref="table"
      :columns="tableColumns"
      height="auto"
      columnsRef="partPartPurchasePurchaseOrderCreateOrderMain"
      :dataSource="partDetailList"
      :isMemoryPagination="true"
      :isExportExcel="true"
      :exportFileName="'配件采购订单数据.xlsx'"
      :pageSize="40"
      :onCellChange="tableCellChange"
      :onSyncTableData="handleTableDataListChange"
      :onRowSelectChange="handleTableRowSelect"
      :onColumnsChange="columns => (this.tableColumns = columns)"
    >
      <template slot="moreActions">
        <span v-if="!editData.cConfirm && !orderTypeIsSetMeal" size="small" @click="handleDeleteRowData">删除明细</span>
      </template>
      <template slot="controls">
        <el-button size="small" type="primary" :disabled="addDetailBtnDisabled || orderTypeIsSetMeal || editData.cConfirm" icon="el-icon-plus" @click="hanldeAddPart">增加明细</el-button>
        <!-- <el-button size="small" type="danger" :disabled="editData.cConfirm" @click="handleDeleteRowData">删除明细</el-button> -->
      </template>
    </FilterTable>
    <div class="btnWrap">
      <el-button size="small" @click="closeDrawer">关闭</el-button>
      <UploadFile
        style="margin: 0 10px;"
        :initial-value="fileInitalValue"
        isOnlyButton
        :disabled="orderTypeIsSetMeal"
        :actionUrl="`${server.DMSCLOUD_PART}/partPurchase/importPart`"
        @change="handleUploadChange"
        >Excel导入</UploadFile
      >
      <AjaxButton type="primary" size="small" :click="handleExportTemplate">导出模板</AjaxButton>
      <el-button type="primary" size="small" :disabled="isAdd || editData.cConfirm" @click="handleDeleteOrder">订单删除</el-button>
      <AjaxButton type="primary" size="small" :disabled="isAdd || editData.cConfirm" :click="handleLockOrder">锁定订单</AjaxButton>
      <AjaxButton type="primary" size="small" :disabled="isAdd || !editData.cConfirm" :click="handleUnlockOrder">取消锁定</AjaxButton>
      <AjaxButton type="primary" size="small" :disabled="editData.cConfirm" :click="handleSyncPartMainFile">同步配件主文件</AjaxButton>
      <AjaxButton type="primary" size="small" :disabled="isAdd || !editData.cConfirm" :click="handleOrderUpload">订单上传</AjaxButton>
      <AjaxButton type="primary" size="small" :disabled="editData.cConfirm" :click="saveOrder">保存</AjaxButton>
      <!-- <el-button
        type="primary"
        size="small"
        :disabled="isAdd"
        @click="handleUpadateOrderStatus"
      >修改状态</el-button>-->
    </div>

    <!-- 选择单据弹框 -->
    <BaseDialog :visible.sync="billSelectVisible" :title="'选择' + selectedOrderTypeName" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <billSelect :billTypeList="billTypeList" :billTypeId="selectedBillsType" @onConfirm="handleBillSelectConfirm" @close="billSelectVisible = false" />
    </BaseDialog>

    <!-- 供应商选择弹窗 -->
    <BaseDialog :visible.sync="showSupplierSelecter" title="供应商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <provideSearchHelper @close="showSupplierSelecter = false" @onConfirm="handleSupplierSelect" />
    </BaseDialog>

    <!-- 增加配件明细弹窗 -->
    <BaseDialog width="80%" :visible.sync="partSelectVisible" title="增加明细" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partSelect :fetchapi="partSelectFetchApi" :showConfirmBtn="false" :orderType="selectedOrderType" @close="partSelectVisible = false" @onConfirm="handleDetailSelectConfirm" />
    </BaseDialog>

    <!-- 打包订货弹窗 -->
    <BaseDialog
      :visible.sync="packagingOrderVisible"
      title="打包订货"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      @close="packagingOrderVisible = false"
    >
      <packingOrder :partList="packagePartList" @close="packagingOrderVisible = false" @onConfirm="handlePackageOrderConfirm" />
    </BaseDialog>

    <!-- 套餐选择弹窗 -->
    <BaseDialog :visible.sync="setMealSelectVisible" title="选择套餐" :destroyOnClose="true" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <setMealSelect @close="setMealSelectVisible = false" @onConfirm="handleSetMealSelectConfirm"></setMealSelect>
    </BaseDialog>

    <!-- 批量订货 -->
    <BaseDialog
      width="80%"
      :visible.sync="batchPartSelectVisible"
      title="批量订货"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      @viewportChange="hanldeBatchPartDialogChange"
    >
      <batchPartSelect :dialogStatus="batchPartSelectDialogType" :orderNo="billNo" @close="batchPartSelectVisible = false" @onConfirm="handleDetailSelectConfirm"></batchPartSelect>
    </BaseDialog>

    <!-- 接收参考单据明细 -->
    <!-- :title="selectedOrderTypeName + '明细'" -->
    <BaseDialog :visible.sync="receiveBillDetailVisible" title="单据编号" :destroyOnClose="true" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <receiveBillDetail :billTypeId="selectedBillsType" :dataList="billDetailPartList" @close="receiveBillDetailVisible = false" @coalescentConfirm="handleDetailSelectConfirm"></receiveBillDetail>
    </BaseDialog>

    <!-- 推式建议 -->
    <BaseDialog
      :visible.sync="pushSuggestVisible"
      title="推式建议"
      :destroyOnClose="true"
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      @viewportChange="hanldePushSuggestDialogChange"
    >
      <pushSuggestList :dialogStatus="pushSuggestDialogType" @close="pushSuggestVisible = false" @onConfirm="handlePushSuggestPartConfirm"></pushSuggestList>
    </BaseDialog>

    <!-- 选择vin码弹窗 -->
    <BaseDialog :visible.sync="vinSelectVisible" title="选择底盘号" :destroyOnClose="true" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <vinSelect :pIndex="choseVinPartIndex" @close="vinSelectVisible = false" @onConfirm="handleVinSelectConfirm"></vinSelect>
    </BaseDialog>

    <!-- 资金预测打印 -->
    <div v-if="printShow">
      <BasePrint ref="print" direction="horizontal" :data="fundForecastPrintData" template="part/partPurchase/purchaseOrder/templateFundForecastPrint" />
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { formatdate, messageAction, notifyAction, confirmAction, exportExcelFile } from '@/utils';
import SERVER from '@/api/server';
import { queryTex } from '@/api/part/common';

import {
  queryAllOrderTypeInfo,
  saveNewOrder,
  queryAllBillsType,
  queryOrderPartDetailByOrderNo,
  lockOrder,
  unLockOrder,
  queryBllDetailById,
  queryPartListByOrderType,
  fundForecast,
  fundForecastPartList,
  syncPartMainFile,
  updateOrderStatus,
  uploadOrder,
  queryPackingParts,
  updateOrder,
  queryOrderInforByNo,
  queryDefaultOrderList,
  queryPlanOrderDetailById,
  queryBorrowOrderDetailById,
  deleteOrder,
  checkOrderNeedSplit,
  saveSplitOrder,
  querySetMealPartListByTcCode,
  exportTemplate,
  unlockOrderForEdit,
  queryOrderInfoByVin
} from '@/api/part/partPurchase/purchaseOrder';

import provideSearchHelper from './provideSearchHelper';
import partSelect from './partSelect';
import billSelect from './create/billSelect';
import packingOrder from './create/packingOrder';
import setMealSelect from './create/setMealSelect';
import batchPartSelect from './create/batchPartSelect';
import receiveBillDetail from './create/receiveBillDetail';
import pushSuggestList from './create/pushSuggestList';
import vinSelect from './vinSelect';

export default {
  components: {
    billSelect,
    partSelect,
    provideSearchHelper,
    packingOrder,
    setMealSelect,
    batchPartSelect,
    receiveBillDetail,
    pushSuggestList,
    vinSelect
  },
  mixins: [dictionary, authority],
  props: {
    addMode: {
      type: Boolean,
      default: true
    },
    orderNo: {
      type: String,
      default: ''
    },
    partList: {
      type: Array,
      default: []
    },
    // 默认订单类型（默认为普通）
    assignOrderType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      printShow: false,
      isAdd: true,
      server: SERVER,
      purchaseFormList: this.createPurchaseFormList(),
      statusFormList: this.createStatusFormList(),
      billsCreateFormList: this.createBillsCreateFormList(),
      tableColumns: this.createTableColumns(),
      billSelectVisible: false, // 是否显示单据选择弹框
      partSelectVisible: false, // 是否显示明细添加
      showSupplierSelecter: false, // 是否显示供应商弹窗
      packagingOrderVisible: false, // 是否显示打包弹窗
      setMealSelectVisible: false, // 是否显示套餐选择弹窗
      batchPartSelectVisible: false, // 是否显示批量订货弹窗
      receiveBillDetailVisible: false, // 是否显示接收参考单据明细
      pushSuggestVisible: false, // 是否显示推式建议
      vinSelectVisible: false, // 是否显示vin选择弹框

      tax: '', // 税率
      globalLoading: true, // 全局加载状态
      editData: {}, // 订单数据
      billTypeList: [], // 所有单据类型
      billDetailPartList: [], // 单据查询回来的配件列表
      orderTypes: [], // 所有的订单类型
      orderTypesData: {}, // 订单类型数据(key为id，val为内容)
      selectedOrderType: '', // 选中的订单类型(查询配件用)
      partSelectFetchApi: queryPartListByOrderType, // 查询配件api
      orderTypeIsSetMeal: false, // 选中的订单类型是否是促销订单(禁用按钮用)
      selectedSupplierInfo: {
        // 选中的供应商的信息
        customerName: '一汽大众汽车有限公司',
        customerCode: 'FAW-VW'
      },
      partDetailList: [], // 配件的列表数据
      partDetailIdList: [], // 配件列表id数组（比较重复配件，每次列表数据改变时更新）
      partTableSyncData: [], // 同步的table数据
      selectedTableData: [], // 选中的配件列表数据
      packingPartList: [], // 锁定订单时的查询回来回显的打包配件数据
      choseVinPartIndex: 0, // 需要选择vin码的配件index（回填数据用）
      packagePartList: [], // 打包的配件列表
      deletedPartsArr: [], // 删除逇配件列表
      borrowBillsItemIds: '', // 查询详情的借入单的id（通过id传）
      fundForecastPrintData: {}, // 资金预测打印数据
      fileInitalValue: [],
      dataIsEdit: false, // 数据是否编辑（锁定时判断是否能够锁定）
      reQueryOrderNo: '', // 订单编号-重新查询用
      batchPartSelectDialogType: '', // 批量订货弹窗状态 fullscreen 为全屏
      pushSuggestDialogType: '' // 推式建议弹窗状态
    };
  },
  computed: {
    // 订单类型数据是否是套餐(判断增加按钮以及)
    addDetailBtnDisabled() {
      return !!!this.purchaseFormList.find(item => item.fieldName == 'originalOrderType').initialValue;
    },
    selectedBillsType() {
      return this.billsCreateFormList.find(item => item.fieldName == 'a1').initialValue;
    },
    // 选中的订单类型(值)
    selectedOrderTypeVal() {
      return this.purchaseFormList.find(item => item.fieldName == 'originalOrderType').initialValue;
    },
    // 选中的单据类型(名称)
    selectedOrderTypeName() {
      return this.createDictText(this.billsCreateFormList.find(item => item.fieldName == 'a1').initialValue, '9703') || '单据';
    },
    // 订单锁定状态
    orderIsLock() {
      return this.editData.cConfirm;
    },
    // 订购数量
    setMealOrderQuantity() {
      return this.purchaseFormList.find(item => item.fieldName == 'npackageQty').initialValue;
    },
    // 订单编号
    billNo() {
      return this.purchaseFormList.find(item => item.fieldName == 'orderNo').initialValue || '';
    }
    // 是否禁用输入发动机号（三方订单且供应商代码为4KF,且工单未锁定）
    // 调整为只校验锁定状态
    // vEngineNoIsLock() {
    // return !!!(this.selectedSupplierInfo.customerCode === '4KF' && this.selectedOrderTypeVal === 13 && !this.orderIsLock);
    // }
  },
  watch: {
    selectedOrderTypeVal(newval, oldval) {
      this.orderTypeIsSetMeal = newval == 0;
      // 订单类型为套餐类型的订单修改表单验证条件
      let packageFormItem = this.purchaseFormList.find(item => item.fieldName == 'nPackageId');
      let packageNumFormItem = this.purchaseFormList.find(item => item.fieldName == 'npackageQty');

      packageFormItem.rules = this.orderTypeIsSetMeal ? [{ required: true, message: '请选择套餐', trigger: 'blur' }] : [];
      packageNumFormItem.rules = this.orderTypeIsSetMeal ? [{ required: true, message: '请填写订购数量', trigger: 'blur' }] : [];

      packageFormItem.disabled = !(newval == 0) || this.orderIsLock;
      packageNumFormItem.disabled = !(newval == 0) || this.orderIsLock;

      this.changeTableRowEditable(!this.orderTypeIsSetMeal);

      if (!this.orderTypeIsSetMeal) {
        packageFormItem.initialValue = '';
        packageNumFormItem.initialValue = '';
        // 重置表单验证状态
        this.$refs.purchaseForm.$refs.form.clearValidate();
      }
    },
    partTableSyncData(newVal, oldVal) {
      this.purchaseFormList.find(item => item.fieldName == 'originalOrderType').disabled = !!newVal.length;
    },
    orderTypeIsSetMeal(newval, oldval) {
      console.log(newval, oldval);
    },
    // 监听订单锁定状态（修改表单与table可编辑装填）
    orderIsLock(newVal, oldVal) {
      this.changeFormEditable(newVal);
      // 修改table可编辑状态(非锁定并且不是套餐订单)
      this.changeTableRowEditable(!newVal && !this.orderTypeIsSetMeal);
      this.statusFormList.find(item => item.fieldName == 'cConfirm').initialValue = newVal + '';
      this.$refs.table.SET_CELL_DISABLED(this.partTableSyncData, 'vEngineNo', newVal); // 锁定禁用编辑发动机号
    },
    // 监听订购数量变化修改采购数量(套餐订单)
    setMealOrderQuantity(newVal, oldVal) {
      if (newVal && this.selectedOrderTypeVal == 0) {
        this.partTableSyncData.map(item => {
          item.nOrderQty = item.inCount * newVal;
        });
      }
    },
    addMode(newVal) {
      this.isAdd = newVal;
    }
    // vEngineNoIsLock(newVal, oldVal) {
    //   this.$refs.table.SET_CELL_DISABLED(this.partTableSyncData, 'vEngineNo', newVal);
    // }
  },
  created() {
    this.queryTax();
    this.getAllOrderTypeDetail();
    // this.getAllBillsType();
    this.isAdd = this.addMode;
  },
  mounted() {
    if (this.partList.length) {
      let parts = JSON.parse(JSON.stringify(this.partList));
      this.formatPartsData(parts);
      // this.partDetailList = this.partDetailList.concat(parts);
      this.$refs.table.EXECUTE_INSERT(parts); // 调整table数据插入方式为组件标准方法
    }
    if (this.orderNo) {
      this.reQueryOrderNo = this.orderNo;
      this.initEditData(this.orderNo);
    } else {
      // 修复默认新建订单时不能输入不含税单价的问题
      this.changeTableRowEditable(!this.orderTypeIsSetMeal);
    }
  },
  methods: {
    createBillsCreateFormList() {
      return [
        {
          type: 'SELECT',
          label: '单据类型',
          fieldName: 'a1',
          disabled: false,
          itemList: this.createDictList('9703'),
          change: () => {
            this.billsCreateFormList.find(item => item.fieldName == 'a2').initialValue = '';
          }
        },
        {
          type: 'INPUT',
          label: '单据编号',
          fieldName: 'a2',
          disabled: false,
          placeholder: '请选择...',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.showBillSelect}></el-button>;
          },
          readonly: true
        },
        {
          type: 'INPUT',
          fieldName: 'a3',
          label: '',
          labelWidth: '0px',
          render: params => {
            return (
              <el-button type="primary" size="mini" style="margin-bottom: 10px" disabled={this.editData.cConfirm} onClick={this.handleGetBillDetail}>
                接收参考单据明细
              </el-button>
            );
          }
        }
      ];
    },
    // 创建采购订单表单
    createPurchaseFormList() {
      return [
        {
          type: 'INPUT',
          label: '订单采购编号',
          fieldName: 'orderNo',
          disabled: true
        },
        {
          type: 'DATE',
          label: '制单日期',
          fieldName: 'dCreate',
          disabled: true,
          initialValue: new Date()
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'vTransport',
          disabled: false,
          rules: [{ required: true, message: '请选择运输方式', trigger: 'blur' }],
          initialValue: 81141001,
          itemList: this.createDictList('8114')
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'originalOrderType',
          clearable: false,
          initialValue: 1,
          disabled: false,
          rules: [{ required: true, message: '请选择订单类型', trigger: 'blur' }],
          itemList: []
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'vOrderStatus',
          itemList: this.createDictList('8133'),
          // disabled: this.isAdd,
          disabled: true,
          initialValue: 81331001
        },
        {
          type: 'INPUT',
          label: '供应商',
          fieldName: 'nSupplyId',
          rules: [{ required: true, message: '请选择供应商', trigger: 'change' }],
          placeholder: '请选择...',
          initialValue: '一汽大众汽车有限公司',
          disabled: false,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.selectSupplier}></el-button>;
          },
          readonly: true
        },
        {
          type: 'INPUT',
          label: '套餐',
          fieldName: 'nPackageId',
          placeholder: '请选择...',
          rules: [],
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={() => (this.setMealSelectVisible = true)}></el-button>;
          },
          disabled: true,
          readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '订购数量',
          fieldName: 'npackageQty',
          rules: [],
          // precision: 0,
          min: 0,
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          selfCols: 2,
          disabled: false,
          fieldName: 'remark'
        }
      ];
    },
    createStatusFormList() {
      return [
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'vBillStatus',
          itemList: this.createDictList('8100'),
          disabled: true
        },
        {
          type: 'SELECT',
          label: '配件删除状态',
          fieldName: 'a2',
          itemList: [
            { text: '00', value: '1' },
            { text: '11', value: '2' }
          ],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '拒绝原因',
          fieldName: 'a3',
          disabled: true
        },
        {
          type: 'DATE',
          label: '提交日期',
          fieldName: 'dSubmit',
          dateFormat: 'yyyy-MM-dd',
          disabled: true
        },
        {
          type: 'CHECKBOX',
          label: '锁定',
          fieldName: 'cConfirm',
          options: {
            trueValue: 'true',
            falseValue: 'false'
          },
          selfCols: 0.5,
          disabled: true
        },
        {
          type: 'CHECKBOX',
          label: '上传',
          fieldName: 'cUpload',
          selfCols: 0.5,
          options: {
            trueValue: 'true',
            falseValue: 'false'
          },
          disabled: true
        },
        {
          type: 'INPUT',
          label: '上传状态',
          fieldName: 'a7',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '确认人',
          fieldName: 'a8',
          disabled: true
        },
        {
          type: 'DATE',
          label: '确认日期',
          fieldName: 'a9',
          disabled: true
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '行项',
          dataIndex: 'index',
          sorter: true,
          // filter: true,
          width: 120,
          render: params => {
            return <span>{params.row.$index + 1}</span>;
          }
        },
        {
          title: '配件代码',
          width: 150,
          dataIndex: 'partNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'partName',
          widht: 150,
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订货数量',
          dataIndex: 'nOrderQty',
          editable: true,
          defaultEditable: true,
          editType: 'number',
          min: 0,
          summation: true,
          sorter: true,
          filter: true,
          filterType: 'number'
          // editDisableRender: params => {
          //   return <el-input disabled={this.orderIsLock} value={params.row.nOrderQty}></el-input>;
          // }
        },
        {
          title: '含税采购单价',
          dataIndex: 'planPrice',
          precision: 2,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税采购单价',
          dataIndex: 'nPriceNoTax',
          precision: 2,
          editable: false,
          defaultEditable: false,
          editType: 'number',
          sorter: true,
          filter: true,
          filterType: 'number'
          // editDisableRender: params => {
          //   return <el-input value={params.row.nPriceNoTax}></el-input>;
          // }
        },
        {
          title: '含税采购金额',
          dataIndex: 'total_planPrice',
          precision: 2,
          summation: true,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '不含税采购金额',
          dataIndex: 'total_nPriceNoTax',
          precision: 2,
          summation: true,
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '发动机号',
          dataIndex: 'vEngineNo',
          editable: true,
          defaultEditable: true,
          maxlength: 10,
          editType: 'text',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '底盘号',
          dataIndex: 'vVin',
          minWidth: 350,
          render: params => {
            return (
              <el-input
                onInput={val => {
                  params.row.vVin = val;
                }}
                disabled={this.orderIsLock}
                placeholder="请选择..."
                value={params.row.vVin}
                size="mini"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  onClick={() => {
                    this.handlePartChoseVin(params.row);
                  }}
                ></el-button>
              </el-input>
            );
          },
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '仅辖区发货',
          dataIndex: 'shipMark',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '建议数量',
          dataIndex: 'nSuggestQty',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '欠料数量',
          dataIndex: 'a9',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '需求日期',
          dataIndex: 'dDemand',
          width: 150,
          editable: true,
          defaultEditable: true,
          editType: 'date-picker',
          dateFormat: 'yyyy-MM-dd',
          editRequired: true,
          sorter: true,
          filter: true,
          filterType: 'date-range'
          // editDisableRender: params => {
          //   return <el-date-picker disabled={this.orderIsLock} value={params.row.dDemand}></el-date-picker>;
          // }
        },
        {
          title: '主组号',
          dataIndex: 'a14',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '原始订单号',
          dataIndex: 'vOldBillNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '分店订货数量',
        //   dataIndex: 'nSubOrderQty'
        // },
        {
          title: '到货数量',
          dataIndex: 'nArrivalQty',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '操作员',
          dataIndex: 'a18',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'ETKA',
          dataIndex: 'a19',
          align: 'center',
          render: params => {
            return <el-checkbox disabled={true} checked={!!params.row.cEtka}></el-checkbox>;
          },
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '委托书编号',
          dataIndex: 'vSvcBillNo',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修日期',
          dataIndex: 'dEnter',
          dateFormat: 'yyyy-MM-dd',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        },
        {
          title: '厂家处理说明',
          dataIndex: 'vSuhandleDesc',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'R3三包采购',
          dataIndex: 'a23',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    // 查询税率
    async queryTax() {
      let res = await queryTex();
      this.tax = res.data;
    },
    // 点击推式建议按钮
    handlePushSuggestBtnClick() {
      this.pushSuggestVisible = true;
    },
    // 禁用或开启table行项输入
    changeTableRowEditable(val = false) {
      let indexList = ['nPriceNoTax', 'nOrderQty', 'dDemand'];
      indexList.map(item => {
        this.tableColumns.find(item2 => item2.dataIndex == item).editable = val;
        this.tableColumns.find(item2 => item2.dataIndex == item).defaultEditable = val;
        // this.tableColumns.find(item2 => item2.dataIndex == item).editRequired = val;
      });
    },
    // 禁用或开启表单项可编辑状态（锁定，取消锁定使用）
    changeFormEditable(val = false) {
      this.billsCreateFormList.map(item => {
        item.disabled = val;
      });
      let purchaseFormNeedDisableList = ['vTransport', 'nSupplyId', 'remark']; // 表单中需要修改编辑状态的字段
      purchaseFormNeedDisableList.map(item => {
        this.purchaseFormList.find(item2 => item2.fieldName == item).disabled = val;
      });

      // 订单类型是套餐的情况单独处理
      if (this.addDetailBtnDisabled) {
        let billOrderFormItem = ['nPackageId', 'npackageQty'];
        billOrderFormItem.map(item => {
          this.purchaseFormList.find(item2 => item2.fieldName == item).disabled = val;
        });
      }
    },
    // 推式建议点击确定
    handlePushSuggestPartConfirm(e) {
      let orderType = this.purchaseFormList.find(item => item.fieldName == 'originalOrderType');
      // 订单维推式订单直接增加配件，否则清空配件列表重新添加
      if (orderType.itemList.find(item => item.value == orderType.initialValue).text == '推式订单') {
        this.handleDetailSelectConfirm(e);
      } else {
        this.$refs.table.EXECUTE_DELETE(this.partTableSyncData);
        this.handleDetailSelectConfirm(e);
      }
      orderType.initialValue = orderType.itemList.find(item => item.text == '推式订单').value;
    },
    // 点击资金预测按钮
    async handleFundForecast() {
      this.printShow = true;
      let amountPlanData = {},
        amountPlanItemData = [],
        totalAmountData = {};
      // 获取预测资金信息
      try {
        let res = await fundForecast();
        if (res.resultCode == 200) {
          amountPlanData = res.data[0] || [];
        }
      } catch (err) {
        console.log(err, '获取预测资金信息失败');
      }
      // 获取预测配件信息
      try {
        let res2 = await fundForecastPartList();
        if (res2.resultCode == 200) {
          amountPlanItemData = res2.data;
          // 计算合计金额数量
          let amountObj = { TOTAL_AMOUNT_1: 0, TOTAL_AMOUNT_2: 0, TOTAL_AMOUNT_3: 0, TOTAL_AMOUNT_4: 0, TOTAL_AMOUNT_5: 0, TOTAL_AMOUNT_6: 0 };
          let countObj = { TOTAL_COUNT_1: 0, TOTAL_COUNT_2: 0, TOTAL_COUNT_3: 0, TOTAL_COUNT_4: 0, TOTAL_COUNT_5: 0, TOTAL_COUNT_6: 0 };
          res2.data.map(item => {
            amountObj.TOTAL_AMOUNT_1 += item.AMOUNT_1;
            amountObj.TOTAL_AMOUNT_2 += item.AMOUNT_2;
            amountObj.TOTAL_AMOUNT_3 += item.AMOUNT_3;
            amountObj.TOTAL_AMOUNT_4 += item.AMOUNT_4;
            amountObj.TOTAL_AMOUNT_5 += item.AMOUNT_5;
            amountObj.TOTAL_AMOUNT_6 += item.AMOUNT_6;

            countObj.TOTAL_COUNT_1 += item.ZJYSL_1;
            countObj.TOTAL_COUNT_2 += item.ZJYSL_2;
            countObj.TOTAL_COUNT_3 += item.ZJYSL_3;
            countObj.TOTAL_COUNT_4 += item.ZJYSL_4;
            countObj.TOTAL_COUNT_5 += item.ZJYSL_5;
            countObj.TOTAL_COUNT_6 += item.ZJYSL_6;
          });
          totalAmountData = {
            ...amountObj,
            ...countObj
          };
        }
      } catch (err) {
        console.log(errm, '获取预测配件信息失败');
      }
      this.fundForecastPrintData = {
        amountPlanData,
        amountPlanItemData,
        totalAmountData
      };
      this.$nextTick(() => {
        this.$refs.print.EXCUTE_PRINT();
      });
    },
    // 显示打包订货选择框
    showPackgingOrder() {
      this.packagingOrderVisible = true;
    },
    // 打包订货点击确定
    handlePackageOrderConfirm(e) {
      // console.log(e, '打包订货点击确定');
      // 先根据订购系数赋值采购数量(采购数量*采购系数)
      let countObj = {};
      e.oldIds.map(item => {
        countObj[item] = this.partTableSyncData.find(item2 => item2.partNo == item) ? this.partTableSyncData.find(item2 => item2.partNo == item).nOrderQty : 1;
      });
      e.groupPackgParts.map(item => {
        item.nOrderQty = countObj[item.oldPartNo] * (item.quan2 / item.quan1);
      });
      e.relyOnParts.map(item => {
        item.nOrderQty = countObj[item.oldPartNo] * (item.quan2 / item.quan1);
      });
      this.formatPartsData(e.groupPackgParts); // 绑定配件订单字段 初始化值
      // 替换组打包配件（不存在替换的配件的话直接插入）
      e.groupPackgParts.map(item => {
        let replacePart = this.partTableSyncData.find(item2 => item2.partNo == item.oldPartNo);
        replacePart ? this.partTableSyncData.splice(replacePart.$index, 1, item) : e.relyOnParts.push(item);
      });

      // 依赖打包直接插入
      this.handleDetailSelectConfirm(e.relyOnParts);
    },
    // 查询所有订单类型
    async getAllOrderTypeDetail() {
      let res = await queryAllOrderTypeInfo();
      let obj = {};
      let orderTypeDic = res.data.map(item => {
        obj[item.partTypeId] = item;
        return { value: item.partTypeId, text: item.partTypeName };
      });
      this.orderTypesData = obj;
      this.purchaseFormList.find(item => item.fieldName == 'originalOrderType').itemList = orderTypeDic;
      this.orderTypes = res.data;

      if (this.assignOrderType != 1) {
        this.purchaseFormList.find(item => item.fieldName == 'originalOrderType').initialValue = this.assignOrderType * 1;
      }
    },
    // 查询所有单据类型
    async getAllBillsType() {
      let res = await queryAllBillsType();
      if (res.resultCode == 200) {
        let billTypeList = res.data.map(item => ({ text: item.vCorName, value: item.vCorType }));
        this.billsCreateFormList.find(item => item.fieldName == 'a1').itemList = billTypeList;
        this.billTypeList = billTypeList;
      }
    },
    // 单据选择点击确定
    handleBillSelectConfirm(e) {
      // console.log(e);
      let billType = this.billsCreateFormList.find(item => item.fieldName == 'a1').initialValue;
      let selectedBillsInfo = '';
      switch (billType) {
        case 97031001:
          selectedBillsInfo = e.map(item => item.vBillNo);
          let itemIdss = e.map(item => item.itemId);
          this.borrowBillsItemIds = itemIdss.join(',');
          break;
        case 97031003:
          selectedBillsInfo = e.map(item => item.allocateInNo);
          let itemIds = e.map(item => item.itemId);
          this.borrowBillsItemIds = itemIds.join(',');
          break;
      }
      this.billsCreateFormList.find(item => item.fieldName == 'a2').initialValue = selectedBillsInfo.join(',');
    },
    // 点击接收参考单据明细
    async handleGetBillDetail() {
      let type = this.billsCreateFormList.find(item => item.fieldName == 'a1').initialValue;
      // let billNos = type == 97031003 ? this.borrowBillsItemIds : this.billsCreateFormList.find(item => item.fieldName == 'a2').initialValue;
      let billNos = this.borrowBillsItemIds;
      if (!type) {
        notifyAction('请先选择单据类型', 'warning');
        return;
      } else if (!billNos && type != 97031002) {
        notifyAction('请先选择单据', 'warning');
        return;
      }
      let fetchapi = '';
      if (type == 97031002) {
        fetchapi = queryDefaultOrderList;
      } else if (billNos) {
        switch (type) {
          case 97031001:
            fetchapi = queryPlanOrderDetailById;
            break;
          case 97031003:
            fetchapi = queryBorrowOrderDetailById;
            break;
        }
      }
      let res = await fetchapi({
        vBillNo: billNos
      });
      if (type == 97031001) {
        if (!this.tax) {
          let tax = await queryTex();
          this.tax = tax.data || 0.13;
        }
        res.data.map(item => (item.planPrice = item.planPrice / (1 + Number(this.tax)))); // 订单采购计划去除税
      }
      this.billDetailPartList = res.data;

      this.receiveBillDetailVisible = true;
    },
    // 关闭新建弹框
    closeDrawer() {
      this.$emit('drawerChange', false);
      // 非编辑时取消订单锁定状态
      // if (!this.isAdd) {
      //   unlockOrderForEdit(this.editData.itemId);
      // }
    },
    // 初始化编辑数据
    async initEditData(orderNo) {
      this.$refs.table.START_LOADING();
      let orderInfo = await queryOrderInforByNo({
        orderNo
      });
      this.editData = orderInfo.data[0];

      this.setFormListInitValue(this.purchaseFormList);
      this.setFormListInitValue(this.statusFormList);
      this.setFormListInitValue(this.billsCreateFormList);

      // try {
      //   this.purchaseFormList.find(item => item.fieldName == 'dCreate').initialValue = new Date(this.editData.dCreate);
      // } catch (err) {
      //   console.log(err);
      // }

      // 供应商单独处理
      this.purchaseFormList.find(item => item.fieldName == 'nSupplyId').initialValue = this.editData.customerName;
      this.selectedSupplierInfo = {
        name: this.editData.customerName,
        customerCode: this.editData.nSupplyId
      };
      // 上传状态单独处理
      this.statusFormList.find(item => item.fieldName == 'cUpload').initialValue = (!!this.editData.cUpload == true) + '';

      let res = await queryOrderPartDetailByOrderNo({
        orderNo: this.editData.orderNo
      });
      if (this.editData.originalOrderType == '0') {
        res.data.map(item => {
          item.inCount = item.nOrderQty / this.editData.npackageQty;
        });
      }
      this.partDetailList = res.data;
      console.log(this.partDetailList, 'table数据变化');
      this.$nextTick(() => {
        this.reCalculateTableData();
        this.$refs.table.STOP_LOADING();
      });
    },
    // 循环表单list字段编辑初始化赋值
    setFormListInitValue(data) {
      data.map(item => {
        if (this.editData[item.fieldName]) {
          let target = data.find(item2 => item2.fieldName == item.fieldName);
          // 如果数据字符都是数字的话将其转为number类型(防止选择框类型回显失败)
          target.initialValue = /^\d+(\.\d+)?$/.test(this.editData[item.fieldName]) ? this.editData[item.fieldName] * 1 : this.editData[item.fieldName];
        }
      });
    },
    // 点击单据编号选择
    showBillSelect() {
      // 欠料单单独处理
      let billtype = this.billsCreateFormList.find(item => item.fieldName == 'a1').initialValue;
      if (billtype) {
        if (billtype == 97031002) {
          this.handleGetBillDetail();
        } else {
          this.billSelectVisible = true;
        }
      } else {
        notifyAction('请先选择单据类型', 'warning');
      }
    },
    // 点击选择供应商
    selectSupplier() {
      this.showSupplierSelecter = true;
    },
    // 供应商选择点击确定
    handleSupplierSelect(e) {
      // console.log(e);
      this.selectedSupplierInfo = e;
      this.purchaseFormList.find(item => item.fieldName == 'nSupplyId').initialValue = e.customerName; // 实际值应该为customerCode(提交时需要覆盖
    },
    // 套餐选择点击确定
    async handleSetMealSelectConfirm(e) {
      this.partDetailList = [];
      this.purchaseFormList.find(item => item.fieldName == 'nPackageId').initialValue = e[0].tcCode;

      this.$refs.table.START_LOADING();
      try {
        let res = await querySetMealPartListByTcCode({
          tcCode: e[0].tcCode
        });
        console.log(res);
        this.$refs.table.STOP_LOADING();
        if (res.resultCode == 200) {
          if (res.data.length) {
            this.formatPartsData(res.data);
            this.handleDetailSelectConfirm(res.data);
          } else {
            notifyAction('此套餐暂无配件信息，请更换其他套餐', 'warning');
          }
        }
      } catch (err) {
        this.$refs.table.STOP_LOADING();
        console.log(err, '查询套餐下配件明细失败');
      }
    },
    // 点击增加明细
    hanldeAddPart() {
      this.selectedOrderType = this.purchaseFormList.find(item => item.fieldName == 'originalOrderType').initialValue;
      this.partSelectVisible = true;
    },
    // 往配件table列表中插入数据
    handleDetailSelectConfirm(e) {
      let partList = e;
      let orderType = this.purchaseFormList.find(item => item.fieldName == 'originalOrderType').initialValue;
      let limitRow = this.orderTypesData[orderType].maxRow;
      let allowRepetition = this.orderTypesData[orderType].isRepeat;

      // 校验重复配件
      let newPartArr = [],
        repeatingPartArr = []; // 重复配件，新配件
      if (!allowRepetition) {
        partList.map(item => {
          if (this.partDetailIdList.indexOf(item.partNo) > -1) {
            repeatingPartArr.push(item);
          } else {
            newPartArr.push(item);
          }
        });
      } else {
        newPartArr = partList;
      }

      if (repeatingPartArr.length) {
        let idsArr = repeatingPartArr.map(item => item.partNo);
        repeatingPartArr.map(item => {
          this.partTableSyncData.find(item2 => item2.partNo == item.partNo).nOrderQty = item.nOrderQty;
          this.partTableSyncData.find(item2 => item2.partNo == item.partNo).total_planPrice = this.partTableSyncData.find(item2 => item2.partNo == item.partNo).planPrice * item.nOrderQty;
          this.partTableSyncData.find(item2 => item2.partNo == item.partNo).total_nPriceNoTax = this.partTableSyncData.find(item2 => item2.partNo == item.partNo).nPriceNoTax * item.nOrderQty;
        });
        notifyAction('此订单类型禁止添加重复配件,订货数量已覆盖，配件代码：' + idsArr.join(','), 'warning');
      }

      // 校验添加数量
      if (limitRow && this.partTableSyncData.length > limitRow + newPartArr.length) {
        notifyAction('此类型订单最多添加' + limitRow + '条配件信息');
        return;
      }

      newPartArr = JSON.parse(JSON.stringify(newPartArr)); // 浅拷贝防止原始数据修改
      this.formatPartsData(newPartArr);

      this.$refs.table.EXECUTE_INSERT(newPartArr);
      notifyAction('配件添加成功', 'success');
      this.dataIsEdit = true;
      // this.partDetailIdList = partList.map(item => item.partNo);
    },
    // 循环结算传入的列表数组的含税不含税单价（新增配件初始化数据用）
    async formatPartsData(list) {
      if (!this.tax) {
        let tax = await queryTex();
        this.tax = tax.data || 0.13;
      }
      list.map((item, index) => {
        // 处理采购数量，套餐类型单独处理 incount数量x订购套数
        this.$set(list[index], 'nOrderQty', this.selectedOrderTypeVal == 0 ? item.inCount * (this.setMealOrderQuantity || 1) || 1 : item.nOrderQty || item.packageLiaght || 1);
        this.$set(list[index], 'nPriceNoTax', item.planPrice);
        item.planPrice = item.planPrice * (1 + Number(this.tax)); // 新增配件是查询回来的都是不含税单价，单独处理
        this.$set(list[index], 'total_planPrice', item.planPrice * item.nOrderQty);
        this.$set(list[index], 'total_nPriceNoTax', item.nPriceNoTax * item.nOrderQty);
        this.$set(list[index], 'dDemand', item.dDemand || new Date());
        this.$set(list[index], 'vVin', item.vVin || '');
      });
    },
    // 循环计算配件详情配件金额(编辑 修改时同步修改数据)
    async reCalculateTableData() {
      if (!this.tax) {
        let tax = await queryTex();
        this.tax = tax.data || 0.13;
      }
      this.partTableSyncData.map(item => {
        item.nOrderQty = item.nOrderQty || 1;
        item.planPrice = item.nPriceNoTax * (1 + Number(this.tax));
        item.total_planPrice = item.planPrice * item.nOrderQty;
        item.total_nPriceNoTax = item.nPriceNoTax * item.nOrderQty;
      });
    },
    // 同步table列表数据
    handleTableDataListChange(e) {
      // console.log(e, 'table数据');
      this.partDetailIdList = e.map(item => item.partNo);
      // 限制订货数量只能输入整数 暂时去除 hxj 2020/2/29
      // e.map(item => {
      //   item.nOrderQty = Math.round(item.nOrderQty * 1);
      // });
      this.partTableSyncData = e;
      // e.map(item => {
      //   this.$refs.table.SET_CELL_DISABLED(this.partTableSyncData, 'vEngineNo', this.vEngineNoIsLock);
      // });
    },
    // table行项输入改变
    tableCellChange(e) {
      // console.log(e);
      this.dataIsEdit = true;
      this.reCalculateTableData();
    },
    // table选中行数据
    handleTableRowSelect(e) {
      this.selectedTableData = e;
    },
    // 点击选择vin码
    handlePartChoseVin(e) {
      this.choseVinPartIndex = e.$index;
      this.vinSelectVisible = true;
    },
    // 选择vin码点击确认
    async handleVinSelectConfirm(e) {
      // 根据vin查询委托记录信息(委托书号，送修日期)
      try {
        let res = await queryOrderInfoByVin({
          vin: e.carData.vin
        });
        if (res.resultCode == 200 && res.data[0]) {
          this.partTableSyncData[e.index].vSvcBillNo = res.data[0].RO_NO;
          this.partTableSyncData[e.index].dEnter = res.data[0].PICKUP_DATE;
        }
      } catch (err) {
        console.log('根据vin获取委托书信息失败');
      }
      this.partTableSyncData[e.index].vVin = e.carData.vin;
    },
    // 点击删除明细
    handleDeleteRowData() {
      if (!this.selectedTableData.length) return;
      this.deletedPartsArr = this.deletedPartsArr.concat(this.selectedTableData);
      this.$refs.table.EXECUTE_DELETE(this.selectedTableData);
      this.dataIsEdit = true;
      console.log(this.partTableSyncData, '点击删除后的配件列表');
    },
    // 订单提交前验证
    orderCheckOut() {
      // 增加校验销售锁
      let saleLockMarkList = '';
      try {
        if (this.partTableSyncData) {
          this.partTableSyncData.forEach(element => {
            if (element['saleLockMark'] == '1') {
              saleLockMarkList += '<p>行项' + eval(Number(element['$index']) + 1) + '配件' + element['partNo'] + '有销售锁!<p>';
              // throw Error('行项' + eval(Number(element['$index']) + 1) + '配件' + element['partNo'] + '有销售锁');
            }
          });
        }
      } catch (Error) {}
      if (saleLockMarkList.length > 0) {
        notifyAction(saleLockMarkList, 'warning');
        return false;
      }

      // 增加校验发动机号字段为空 去除，改为后端校验 hxj 20200822
      // try {
      //   if (!this.vEngineNoIsLock) {
      //     var vEngineNoArray = [];
      //     this.partTableSyncData.forEach(function(item) {
      //       vEngineNoArray.push(item.vEngineNo);
      //     });
      //     if (vEngineNoArray.includes('')) {
      //       notifyAction('所有发动机均需要打号，请确认', 'warning');
      //       return false;
      //     }
      //   }
      // } catch (Error) {}

      return new Promise((resolve, reject) => {
        // 校验配件列表必填字段
        /**
         * 1.配件号是否允许重复（新增时校验）
         * 2.配件最大行数（新增时校验）
         * 3.订货数量整数倍校验
         * 4.vin码是否输入
         * 5.订购数量是否为0
         * 6.需求日期是否小于制单日期
         */
        let noVinPartList = [],
          noQtyList = [], // 订购数量为0的配件
          amountChekFalseList = [], // vin码未输入配件数据，订货数量不满足要求的数组
          maxAmountChekcFailList = [], // 最大订货数量不符合规则的配件
          dDemandOverPlanDateList = []; // 计划日期大于制单日期的配件
        let orderType = this.orderTypesData[this.purchaseFormList.find(item => item.fieldName == 'originalOrderType').initialValue];
        let orderCreatedTime = this.purchaseFormList.find(item => item.fieldName == 'dCreate').initialValue;
        let nowTimeStamp = new Date(formatdate(new Date(orderCreatedTime), 1)).getTime();

        this.partTableSyncData.map((item, index) => {
          // 校验是否输入vin码
          if (!item.vVin && (item.isCccPart || orderType.isVin)) {
            noVinPartList.push(item);
          }
          // 校验采购数量是否符合规则
          console.log(item.packageLiaght);
          if (orderType.maxCount && item.nOrderQty && item.packageLiaght != null && item.packageLiaght != '') {
            // 不是最小包装数量整数倍
            if (item.nOrderQty % item.packageLiaght != 0) {
              amountChekFalseList.push(item);
            }
            // 订货数量大于订单最大订货数量
            if (item.nOrderQty > orderType.maxCount * item.packageLiaght) {
              maxAmountChekcFailList.push(item);
            }
          }
          if (!item.nOrderQty) {
            noQtyList.push(item);
          }
          // if (item.dDemand && new Date(item.dDemand).getTime() < nowTimeStamp) {
          //   dDemandOverPlanDateList.push(item);
          // }
        });

        // 提示消息
        console.log('订单最大订货数量', orderType.maxCount);
        console.log('未输入vin的配件', noVinPartList);
        console.log('不符合采购数量的配件', amountChekFalseList, maxAmountChekcFailList);
        console.log('采购数量为0的配件', noQtyList);
        console.log('订购日期小于制单日期的配件', dDemandOverPlanDateList);

        let msg = '';
        let noVinIndexArr = noVinPartList.map(item => item.$index + 1);
        let amountChekFalseIndexArr = amountChekFalseList.map(
          item => '<p>行项：' + (item.$index + 1) + '订购数量：' + item.nOrderQty + ',不是该配件最小包装量：' + item.packageLiaght + '的整数倍</p>'
        );
        let maxAmountChekcFailIndexArr = maxAmountChekcFailList.map(
          item => '<p>行项：' + (item.$index + 1) + '订购数量：' + item.nOrderQty + ',大于此订单类型该配件最大订货数量' + orderType.maxCount * item.packageLiaght + '</p>'
        );
        let noQtyCheckFalseIndexArr = noQtyList.map(item => item.$index + 1);
        let dDemandOverPlanDateIndexArr = dDemandOverPlanDateList.map(item => item.$index + 1);

        msg =
          (noVinIndexArr.length ? '<div>未填写vin码的配件行项：' + noVinIndexArr.join(',') + '</div>' : '') +
          (amountChekFalseIndexArr.length ? '<div>订货数量不符合规则的配件行项：' + amountChekFalseIndexArr.join('') + '</div>' : '') +
          (maxAmountChekcFailIndexArr.length ? '<div>订货数量不符合规则的配件行项：' + maxAmountChekcFailIndexArr.join('') + '</div>' : '') +
          (noQtyCheckFalseIndexArr.length ? '<div>订货数量为0的配件行项：' + noQtyCheckFalseIndexArr.join(',') + '</div>' : '') +
          (dDemandOverPlanDateIndexArr.length ? '<div>订购日期小于制单日期的行项：' + dDemandOverPlanDateIndexArr.join(',') + '</div>' : '');

        if (noVinIndexArr.length || amountChekFalseIndexArr.length || noQtyCheckFalseIndexArr.length || dDemandOverPlanDateIndexArr.length || maxAmountChekcFailIndexArr.length) {
          this.$alert(msg, '不符合规则的配件', {
            dangerouslyUseHTMLString: true
          });
          // confirmAction(msg);
          reject(false);
        } else {
          resolve(true);
        }
      });
    },
    // 点击保存订单
    async saveOrder() {
      if (!this.partTableSyncData.length) {
        notifyAction('请添加配件明细', 'warning');
        return;
      }
      // 校验表单必填字段并提示
      let formData = await this.$refs.purchaseForm.GET_FORM_DATA();
      console.log(formData);
      if (formData[0]) {
        let keys = Object.keys(formData[0]);
        console.log(keys);
        notifyAction(formData[0][keys[0]][0].message, 'warning');
        return;
      }

      // 校验配件行项必填字段
      let checkRes = await this.orderCheckOut();
      if (!checkRes) return;

      let formParams = JSON.parse(JSON.stringify(formData[1]));
      // 手动处理部分提交数据
      formParams.nSupplyId = this.selectedSupplierInfo.customerCode;
      if (this.isAdd) {
        formParams.dCreate = formatdate(new Date(formParams.dCreate), 1);
      }

      this.partTableSyncData.map(item => {
        item.nSpaId = item.partNo;
        item.nPurPrice = item.planPrice;
        item.deleteItem = 0;
      });
      this.deletedPartsArr.map(item => {
        item.nSpaId = item.partNo;
        item.nPurPrice = item.planPrice;
        item.deleteItem = 1;
      });

      formParams.itemList = [...this.partTableSyncData, ...this.deletedPartsArr];
      if (!this.isAdd) {
        formParams.orderNo = this.editData.orderNo;
        formParams.itemId = this.editData.itemId;
      }

      if (this.isAdd) {
        let checkResult = await checkOrderNeedSplit(formParams);
        if (checkResult.data.status == 1) {
          confirmAction(checkResult.data.resultMsg, 'warning')
            .then(res => {
              formParams.orderType = checkResult.data.orderType;
              this.saveSubmitSplirOrderFun(formParams);
            })
            .catch(err => {
              console.log('拒绝拆分订单');
            });
        } else {
          this.saveSubmitFun(formParams);
        }
      } else {
        this.saveSubmitFun(formParams);
      }
    },
    // 保存提交函数（直接保存）
    async saveSubmitFun(formParams) {
      // let loadingTarget = this.$loading({
      //   target: this.$refs.wrap
      // });
      this.$refs.table.START_LOADING();
      let res = '';
      try {
        if (this.isAdd) {
          res = await saveNewOrder(formParams);
        } else {
          res = await updateOrder(formParams);
        }
      } catch (err) {
        console.log('编辑订单失败', err);
        // loadingTarget.close();
        this.$refs.table.STOP_LOADING();
      }
      this.$refs.table.STOP_LOADING();
      // loadingTarget.close();

      if (res.resultCode == 200) {
        notifyAction('保存成功', 'success');
        this.deletedPartsArr = [];
        this.dataIsEdit = false;
        if (this.isAdd && res.data.orderNo) {
          this.isAdd = false;
          this.reQueryOrderNo = res.data.orderNo;
          this.initEditData(res.data.orderNo);
        } else {
          this.initEditData(this.reQueryOrderNo);
        }
        this.$emit('resetTableData');
        // this.closeDrawer();
      }
    },
    // 保存提交函数(拆分订单)
    async saveSubmitSplirOrderFun(formParams) {
      let loadingTarget = this.$loading({
        target: this.$refs.wrap
      });
      let res = await saveSplitOrder(formParams);
      loadingTarget.close();
      if (res.resultCode == 200) {
        this.$emit('resetTableData');
        this.closeDrawer();
      }
    },
    // 重置页面状态(点击新建？)
    resetPageData() {
      this.$refs.billCreateForm.RESET_FORM();
      this.$refs.purchaseForm.RESET_FORM();
      this.partDetailList = [];

      // 初始化赋值
      this.purchaseFormList.find(item => item.fieldName == 'dCreate').initialValue = new Date();
      this.purchaseFormList.find(item => item.fieldName == 'vTransport').initialValue = 81141001;
      this.purchaseFormList.find(item => item.fieldName == 'originalOrderType').initialValue = 1;
      this.purchaseFormList.find(item => item.fieldName == 'vOrderStatus').initialValue = 81331001;
      this.purchaseFormList.find(item => item.fieldName == 'nSupplyId').initialValue = '一汽大众汽车有限公司';
      this.selectedSupplierInfo = { customerName: '一汽大众汽车有限公司', customerCode: 'FAW-VW' };
    },
    // 点击锁定订单
    async handleLockOrder() {
      if (this.dataIsEdit) {
        notifyAction('订单中有未保存的更改，请先保存订单才能锁定', 'warning');
        return;
      }

      let packageOrder = await queryPackingParts({
        orderNo: this.editData.orderNo
      });
      if (packageOrder.data.length) {
        let idArr = packageOrder.data.map(item => item.partNo);
        confirmAction('配件' + idArr.join(',') + '有未勾选的组装打包配件，是否继续')
          .then(res => {
            // 点击确定
            this.packagePartList = packageOrder.data;
            this.packagingOrderVisible = true;
          })
          .catch(err => {
            // 点击取消
            this.handleLockOrder();
          });
        return;
      }

      let res = await lockOrder({
        orderNo: this.editData.orderNo
        // itemList: [{nSpaId }]
      });
      if (res.resultCode == 200) {
        this.$emit('resetTableData');
        notifyAction('订单锁定成功', 'success');
        this.editData.cConfirm = true;
        // this.closeDrawer();
      }
    },
    // 点击解锁订单
    async handleUnlockOrder() {
      let res = await unLockOrder({
        orderNo: this.editData.orderNo
      });
      if (res.resultCode == 200) {
        this.$emit('resetTableData');
        notifyAction('订单解锁成功', 'success');
        this.editData.cConfirm = false;
        // this.closeDrawer();
      }
    },
    // 点击同步配件主文件
    async handleSyncPartMainFile() {
      if (this.selectedTableData.length) {
        let partIds = this.selectedTableData.map(item => item.partNo);
        let res = await syncPartMainFile({
          partNo: partIds.join(',')
        });
        if (res.resultCode == 200) {
          this.updateQueryPartInfo(res.data);
          notifyAction('同步成功', 'success');
        }
      } else {
        notifyAction('请选择想要同步的配件', 'warning');
      }
    },
    // 更新查询回来的配件信息（同步配件主文件）
    updateQueryPartInfo(list) {
      list.map(item => {
        let partObj = this.partTableSyncData.find(item2 => item2.partNo == item.partNo);
        if (partObj) {
          partObj.packageLiaght = item.packageLiaght;
          partObj.fibMark = item.fibMark;
          partObj.isCccPart = item.isCccPart;
          partObj.partName = item.partName;
          partObj.saleLockMark = item.saleLockMark;
          partObj.shipMark = item.shipMark;
          partObj.stockLockMark = item.stockLockMark;
        }
      });
    },
    // 点击修改订单状态
    async handleUpadateOrderStatus() {
      let res = await updateOrderStatus({
        partPurchaseDTO: {}
      });
    },
    // 点击订单上传
    async handleOrderUpload() {
      let res = await uploadOrder({
        itemId: this.editData.itemId
      });
      if (res.resultCode == 200) {
        notifyAction('订单上传成功', 'success');
      }
    },
    // 点击删除订单
    async handleDeleteOrder() {
      confirmAction('是否删除整个订单数据', 'warning')
        .then(async confirm => {
          let res = await deleteOrder({
            orderNo: this.editData.orderNo
          });
          if (res.resultCode == 200) {
            notifyAction('删除成功');
            this.$emit('resetTableData');
            this.closeDrawer();
          }
        })
        .catch(err => {
          notifyAction('取消删除', 'info');
        });
    },
    // 导出模板
    async handleExportTemplate() {
      let res = await exportTemplate();
      exportExcelFile(res.data, '配件订单导入模板');
      // console.log(res);
    },
    // 订单导入成功事件
    handleUploadChange(e) {
      console.log('导入文件上传成功', e[0].url);
      this.fileInitalValue = e;
      let excelData = e[0].url;
      if (excelData.length) {
        // this.formatPartsData(excelData);
        this.handleDetailSelectConfirm(excelData);
        notifyAction('配件信息导入成功', 'success');
      }
    },
    // 批量订货弹窗大小变化
    hanldeBatchPartDialogChange(e) {
      // fullscreen/default
      this.batchPartSelectDialogType = e;
    },
    // 推式建议弹窗大小状态
    hanldePushSuggestDialogChange(e) {
      this.pushSuggestDialogType = e;
    }
  }
};
</script>

<style scoped>
h3 {
  position: relative;
  font-weight: bold;
  margin: 10px 0;
}
h3::before {
  content: '';
  display: block;
  width: 35px;
  height: 2px;
  background: #b71434;
  position: absolute;
  left: 0;
  bottom: -2px;
}
.btnWrap {
  /* text-align: right;
  margin-top: 15px; */
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
.billsTitleWrap {
  display: flex;
  align-items: center;
}
.billsTitleWrap h3 {
  margin-right: 15px;
}
.topBtnWrap {
  display: flex;
  justify-content: space-between;
}
</style>
